﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Facebook;
using FBApp.Classes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Threading;
using System.Net;
using System.IO;

namespace FBApp
{
	/// <summary>
	/// Interaction logic for Notifications.xaml
	/// </summary>
	public partial class Notifications : UserControl
	{
        private LoadingIndicator indicator;
		private FacebookClient fbc = null;        

        //Feeds
        public ObservableCollection<NotificationItem> notificationFeed { get; set; }
        public static Dictionary<string, JSONObject> notificationFeedDictionary = new Dictionary<string, JSONObject>();

		public Notifications()
		{
			this.InitializeComponent();
            notificationFeed = new ObservableCollection<NotificationItem>();
            icItems.ItemsSource = notificationFeed; 
		}
		
		public void setFacebookClient(FacebookClient fbc)
		{
			this.fbc = fbc;
		}

        public void setIndicator(LoadingIndicator indicator)
        {
            this.indicator = indicator;
        }

        public void addNotificationFeedItem(JSONObject item)
        {
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                {

                    NotificationItem notificationItem=null;                    
                    if (item.Dictionary["title_text"].ToDisplayableString().Contains("link"))
                    {
                        notificationItem = new NotificationItem(NotificationBalloon.NotificationType.Link, item.Dictionary["title_text"].ToDisplayableString());                        
                    }
                    else if (item.Dictionary["title_text"].ToDisplayableString().Contains("like"))
                    {
                        notificationItem = new NotificationItem(NotificationBalloon.NotificationType.Like, item.Dictionary["title_text"].ToDisplayableString());     
                    }
                    else if (item.Dictionary["title_text"].ToDisplayableString().Contains("comment") || item.Dictionary["title_text"].ToDisplayableString().Contains("wrote"))
                    {
                        notificationItem = new NotificationItem(NotificationBalloon.NotificationType.Comment, item.Dictionary["title_text"].ToDisplayableString());                        
                    }
                    else if (item.Dictionary["title_text"].ToDisplayableString().Contains("relationship"))
                    {
                        notificationItem = new NotificationItem(NotificationBalloon.NotificationType.Relationship, item.Dictionary["title_text"].ToDisplayableString());                        
                    }

                    if (notificationItem != null)
                    {
                        lock (notificationFeed)
                        {
                            notificationFeed.Add(notificationItem);                            
                        }
                    }                                        
                }
            ));
        }

        public List<JSONObject> updateNotificationFeed(string token)
        {
            string baseURL = "https://api.facebook.com/method/notifications.getList?include_read=true";
            baseURL = baseURL + "&access_token=" + token + "&format=json";
            
            Uri url = new Uri(baseURL);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";

            try
            {
                using (HttpWebResponse response
                        = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader
                        = new StreamReader(response.GetResponseStream());

                    JSONObject obj = JSONObject.CreateFromString(reader.ReadToEnd());
                    Dictionary<string, JSONObject> dictionary = obj.Dictionary;
                    JSONObject notifications = dictionary["notifications"];

                    JSONObject[] notificationFeedItems = notifications.Array;
                    List<JSONObject> newItems = new List<JSONObject>();
                    
                    for (int k = 0; k < notificationFeedItems.Length; k++)
                    {
                        if (!notificationFeedDictionary.ContainsKey(notificationFeedItems[k].Dictionary["notification_id"].ToDisplayableString()))
                        {
                            notificationFeedDictionary[notificationFeedItems[k].Dictionary["notification_id"].ToDisplayableString()] = notificationFeedItems[k];
                            newItems.Add(notificationFeedItems[k]);
                        }
                    }
                    
                    //fbc.getNotifier().displayNotification(newItems.Count + " notification items added");
                    
                    return newItems;
                }
            }
            catch (WebException e)
            {
                throw new FacebookAPIException("Server Error", e.Message);
            }
            
        }

        public void refreshUI()
        {
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
            {
                icItems.UpdateLayout();
            }
             ));
        }
			
	}
}